package com.zlc.common.common.service;


import com.zlc.common.core.user.model.vo.MayanPlatUserVo;
import com.zlc.common.model.user.UserInfo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

import static com.zlc.common.common.constant.PlatConstant.LoginConstant.NOW_USER;

public class ContextHolder {
    private static ApplicationContext applicationContext;
    private static ThreadLocal<Map<String, Object>> currentSettings = new InheritableThreadLocal();

    public ContextHolder() {
    }

    public static void clearContext() {
        if (currentSettings.get() != null) {
            currentSettings.remove();
        }
    }


    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T get(String key) {
        Map<String, Object> param = (Map)currentSettings.get();
        return param == null ? null : (T)param.get(key);
    }

    public static void set(String key, Object value) {
        Map<String, Object> param = (Map)currentSettings.get();
        if (param == null) {
            param = new HashMap();
            currentSettings.set(param);
        }

        ((Map)param).put(key, value);
    }

    public static void setDefaultUser(){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserAccount("system");
        userInfo.setUser(new MayanPlatUserVo().setUserAccount("system"));
        set(NOW_USER, userInfo);
    }

    public static void setUser(UserInfo userInfo){
        set(NOW_USER, userInfo);
    }
}